package org.gtesoreria

class DateUtilsService {

    static transactional = true

    public List<Date> getPeriodsBetween(Date from, Date to) {
		def cal = Calendar.instance
		def isTime = true
		def periods = new ArrayList<Date>()
		periods.add(from)
		while(isTime) {
			cal.setTime(from)
			from = cal.getTime();			
			
			cal.add( Calendar.MONTH, 1);
			cal.set( Calendar.DAY_OF_MONTH, 1)
			cal.add(Calendar.SECOND, -1);
			
			def partialTo = cal.getTime();
			if(partialTo > to){
				isTime = false
				periods.add(partialTo)
			}else{
				periods.add(partialTo)
				from = partialTo
			}
		}
		return periods
	}
	public List<Date> getPeriodsBetweenToShow(Date from, Date to) {
		def cal = Calendar.instance
		def isTime = from < to
		def periods = new ArrayList<Date>()
		periods.add(from)
		while(isTime) {
			cal.setTime(from)
			from = cal.getTime();
			
			cal.add( Calendar.MONTH, 1);
			cal.set( Calendar.DAY_OF_MONTH, 1)
			
			def partialTo = cal.getTime();
			if(partialTo > to){
				isTime = false
				periods.add(partialTo)
			}else{
				periods.add(partialTo)
				from = partialTo
			}
		}
		return periods
	}
	
	public Date getNextPeriodo(Date current){
		def cal = Calendar.instance
		cal.setTime(current)
		cal.add(Calendar.MONTH, 1)
		return cal.getTime()
	}
	
 
	public Date getPreviousPeriodo(Date current){
		def cal = Calendar.instance
		cal.setTime(current)
		cal.add(Calendar.MONTH, -1)
		return cal.getTime()
	}
	
	public Date getFirstDayOfTheNextMonth(Date month){
		def cal = Calendar.instance
		cal.setTime(month)
		cal.add( Calendar.MONTH, 1);
		cal.set( Calendar.DAY_OF_MONTH, 1)
		cal.set( Calendar.HOUR, 0);
		cal.set( Calendar.MINUTE, 0)
		cal.set( Calendar.SECOND, 0);
		cal.set( Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public Date getFirstDayOfTheCurrentMonth(){
		def cal = Calendar.instance
		cal.setTime(new Date())
		cal.set( Calendar.DAY_OF_MONTH, 1)
		cal.set( Calendar.HOUR, 0);
		cal.set( Calendar.MINUTE, 0)
		cal.set( Calendar.SECOND, 0);
		cal.set( Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
}

